package site.wlwsjsx.iot_backend.service.impl;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import site.wlwsjsx.iot_backend.dto.EnvHalfHourAggDTO;
import site.wlwsjsx.iot_backend.dto.EnvUploadDTO;
import site.wlwsjsx.iot_backend.dto.LabDetailDTO;
import site.wlwsjsx.iot_backend.dto.WorkstationDetailDTO;
import site.wlwsjsx.iot_backend.entity.*;
import site.wlwsjsx.iot_backend.service.exception.ServiceException;
import site.wlwsjsx.iot_backend.mapper.*;
import site.wlwsjsx.iot_backend.service.EnvInfoService;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

@Service
public class EnvInfoServiceImpl implements EnvInfoService {
    private static final Logger logger = LoggerFactory.getLogger(EnvInfoServiceImpl.class);

    @Resource
    private LabEnvMapper labEnvMapper;
    @Resource
    private LabInfoMapper labInfoMapper;
    @Resource
    private WorkstationInfoMapper workstationInfoMapper;
    @Resource
    private WorkstationEnvMapper workstationEnvMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public void saveEnvData(EnvUploadDTO envUploadDTO) {
        logger.info("开始保存环境数据 - 设备类型: {}, 设备ID: {}",
                envUploadDTO.getDeviceType(), envUploadDTO.getDeviceId());

        try {
            if ("lab".equalsIgnoreCase(envUploadDTO.getDeviceType())) {
                logger.debug("处理实验室环境数据");
                LabEnv labEnv = new LabEnv();
                labEnv.setLabId(Integer.valueOf(envUploadDTO.getDeviceId()));
                labEnv.setTemperature(envUploadDTO.getTemperature());
                labEnv.setHumidity(envUploadDTO.getHumidity());
                labEnv.setSmokeScope(envUploadDTO.getSmokeScope());
                labEnv.setCreateTime(LocalDateTime.now());

                int res = labEnvMapper.insert(labEnv);
                if (res <= 0) {
                    logger.error("保存实验室环境数据失败 - 实验室ID: {}", envUploadDTO.getDeviceId());
                    throw new ServiceException("数据插入异常");
                }
                logger.info("实验室环境数据保存成功 - 实验室ID: {}", envUploadDTO.getDeviceId());

            } else if ("workstation".equalsIgnoreCase(envUploadDTO.getDeviceType())) {
                logger.debug("处理工位环境数据");
                if (envUploadDTO.getUsername() == null || envUploadDTO.getUsername().isEmpty()) {
                    logger.warn("工位环境数据保存失败 - 用户名为空");
                    throw new ServiceException("用户名不能为空");
                }

                UserInfo userInfo = userMapper.selectUserByUsername(envUploadDTO.getUsername());
                if (userInfo == null) {
                    logger.warn("工位环境数据保存失败 - 用户不存在: {}", envUploadDTO.getUsername());
                    throw new ServiceException("用户不存在");
                }

                WorkstationEnv workstationEnv = new WorkstationEnv();
                workstationEnv.setWorkstationCode(envUploadDTO.getDeviceId());
                workstationEnv.setCurUsername(userInfo.getUsername());
                workstationEnv.setTemperature(envUploadDTO.getTemperature());
                workstationEnv.setHumidity(envUploadDTO.getHumidity());
                workstationEnv.setSmokeScope(envUploadDTO.getSmokeScope());
                workstationEnv.setLightIntensity(envUploadDTO.getLightIntensity());
                workstationEnv.setFlameScope(envUploadDTO.getFlameScope());
                workstationEnv.setCreateTime(LocalDateTime.now());

                int res = workstationEnvMapper.insert(workstationEnv);
                if (res <= 0) {
                    logger.error("保存工位环境数据失败 - 工位代码: {}", envUploadDTO.getDeviceId());
                    throw new ServiceException("数据插入异常");
                }
                logger.info("工位环境数据保存成功 - 工位代码: {}", envUploadDTO.getDeviceId());

            } else {
                logger.warn("未知的设备类型: {}", envUploadDTO.getDeviceType());
                throw new IllegalArgumentException("设备类型错误，必须是 'lab' 或 'workstation'");
            }
        } catch (Exception e) {
            logger.error("保存环境数据发生异常 - 设备类型: {}, 设备ID: {}, 错误: {}",
                    envUploadDTO.getDeviceType(), envUploadDTO.getDeviceId(), e.getMessage());
            throw e;
        }
    }

    @Override
    public LabDetailDTO getLabDetail(Integer labId) {
        logger.info("开始查询实验室详情 - 实验室ID: {}", labId);

        try {
            LabDetailDTO labDetailDTO = new LabDetailDTO();

            logger.debug("查询实验室基础信息");
            LabInfo labInfo = labInfoMapper.selectById(labId);
            if (labInfo == null) {
                logger.warn("实验室基础信息不存在 - 实验室ID: {}", labId);
                throw new ServiceException("实验室不存在");
            }

            labDetailDTO.setId(labInfo.getId());
            labDetailDTO.setLabName(labInfo.getLabName());
            labDetailDTO.setLabLocation(labInfo.getLabLocation());
            labDetailDTO.setMaxWorkstation(labInfo.getMaxWorkstation());
            labDetailDTO.setCurStudentNum(labInfo.getCurStudentNum());

            logger.debug("查询实验室环境数据");
            LabEnv labEnv = labEnvMapper.selectLatestByLabId(labId);
            if (labEnv != null) {
                labDetailDTO.setTemperature(labEnv.getTemperature());
                labDetailDTO.setHumidity(labEnv.getHumidity());
                labDetailDTO.setSmokeScope(labEnv.getSmokeScope());
            }

            logger.debug("查询工位列表信息");
            List<WorkstationInfo> workstationInfos = workstationInfoMapper.selectByLabId(labId);
            logger.debug("找到 {} 个工位", workstationInfos.size());

            for (WorkstationInfo workstationInfo : workstationInfos) {
                logger.debug("处理工位信息 - 工位代码: {}", workstationInfo.getWorkstationCode());
                WorkstationDetailDTO workstationDetailDTO = new WorkstationDetailDTO();

                if (workstationInfo != null) {
                    workstationDetailDTO.setId(workstationInfo.getId());
                    workstationDetailDTO.setWorkstationCode(workstationInfo.getWorkstationCode());
                    workstationDetailDTO.setWorkstationStatus(workstationInfo.getWorkstationStatus());
                    workstationDetailDTO.setCurUserId(workstationInfo.getCurUserId());
                    workstationDetailDTO.setPowerStatus(workstationInfo.getPowerStatus());
                    workstationDetailDTO.setLightStatus(workstationInfo.getLightStatus());
                    workstationDetailDTO.setRelayNum1Status(workstationInfo.getRelayNum1Status());
                    workstationDetailDTO.setRelayNum2Status(workstationInfo.getRelayNum2Status());
                }

                if (workstationInfo.getCurUserId() != null) {
                    logger.debug("查询工位使用者信息 - 用户ID: {}", workstationInfo.getCurUserId());
                    UserInfo userInfo = userMapper.selectUserById(workstationInfo.getCurUserId());
                    if (userInfo != null) {
                        workstationDetailDTO.setUsername(userInfo.getUsername());
                        workstationDetailDTO.setRealName(userInfo.getRealName());
                        workstationDetailDTO.setModifyTime(workstationInfo.getModifyTime());
                    }
                }

                logger.debug("查询工位环境数据 - 工位代码: {}", workstationInfo.getWorkstationCode());
                WorkstationEnv workstationEnv = workstationEnvMapper.selectLatestByCode(workstationInfo.getWorkstationCode());
                if (workstationEnv != null) {
                    workstationDetailDTO.setTemperature(workstationEnv.getTemperature());
                    workstationDetailDTO.setHumidity(workstationEnv.getHumidity());
                    workstationDetailDTO.setSmokeScope(workstationEnv.getSmokeScope());
                    workstationDetailDTO.setLightIntensity(workstationEnv.getLightIntensity());
                    workstationDetailDTO.setFlameScope(workstationEnv.getFlameScope());
                }

                if (labDetailDTO.getWorkstations() == null) {
                    labDetailDTO.setWorkstations(new LinkedList<>());
                }
                labDetailDTO.getWorkstations().add(workstationDetailDTO);
            }

            logger.info("实验室详情查询完成 - 实验室ID: {}", labId);
            return labDetailDTO;

        } catch (Exception e) {
            logger.error("查询实验室详情发生异常 - 实验室ID: {}, 错误: {}", labId, e.getMessage());
            throw e;
        }
    }

    /**
     * 获取指定工作站在指定时间范围内的半小时环境聚合数据
     *
     * @param ’workstationCode‘ 工作站编码，用于标识具体的工作站
     * @param startTime         开始时间，查询的起始时间点
     * @param endTime           结束时间，查询的结束时间点
     * @return 返回一个EnvHalfHourAggDTO列表，包含每个半小时时间段的环境聚合数据
     */
    @Override
    public List<EnvHalfHourAggDTO> getHalfHourEnvAgg(Integer labId, LocalDateTime startTime, LocalDateTime endTime) {
        logger.info("开始获取工作站环境聚合数据，工作站id：{}，时间范围：{} - {}", labId, startTime, endTime);
        List<EnvHalfHourAggDTO> aggData = labEnvMapper.selectHalfHourAggByLabIdAndTimeRange(
                labId, startTime, endTime
        );
        logger.info("查询完成，获取到{}条环境聚合数据", aggData.size());
        return aggData;
    }

    @Override
    public List<EnvHalfHourAggDTO> getEnvHistoryWithInterval(Integer labId, Integer count, Integer interval) {
        logger.info("开始获取实验室环境聚合数据，实验室ID：{}，数量：{}，间隔：{}分钟", labId, count, interval);
        List<EnvHalfHourAggDTO> history = labEnvMapper.selectEnvHistoryWithInterval(labId, count, interval);
        logger.info("查询完成，获取到{}条环境聚合数据", history.size());
        return history;
    }
}
